/**
 * Copyright (C) 2008 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.wsgi.context;

import static cc.aileron.wsgi.context.HttpThreadLocalContext.localContext;

import java.util.HashMap;

import javax.servlet.http.HttpSession;

import com.google.inject.Provider;

/**
 * provider : wsgi-session-context
 * 
 * @author Aileron
 * 
 */
public class ContextProviderSession implements Provider<WsgiSessionContext>
{
    @Override
    public WsgiSessionContext get()
    {
        return new WsgiSessionContext()
        {
            @SuppressWarnings("unchecked")
            @Override
            public <T> T get(final Class<T> targetClass)
            {
                return (T) getMap().get(targetClass);
            }

            @Override
            public void set(final Class<?> targetClass, final Object target)
            {
                if (targetClass != null && target != null)
                {
                    getMap().put(targetClass, target);
                }
            }
        };
    }

    @SuppressWarnings("unchecked")
    HashMap<Class<?>, Object> getMap()
    {
        final HttpSession session = localContext.get().request.getSession(true);
        final HashMap<Class<?>, Object> map = (HashMap<Class<?>, Object>) session
                .getAttribute(this.toString());
        if (map == null)
        {
            final HashMap<Class<?>, Object> blankMap = new HashMap<Class<?>, Object>();
            session.setAttribute(this.toString(), blankMap);
            return blankMap;
        }
        return map;
    }
}